import json

from flask import Flask, render_template, request

from sql_util import *
from user import User

app = Flask(__name__)


@app.route("/")
def page():
    return render_template('user_manager.html')


@app.route("/api/users", methods=['get'])
def get_users():
    user_list = []
    for user in get('select * from user where status = 1'):
        user_list.append(User(*user).to_dict())
    return user_list


@app.route("/api/users", methods=['post'])
def create_user():
    username = request.json.get('username')
    email = request.json.get('email')
    try:
        insert(f"insert into user(username,email) values ('{username}','{email}')")
    except pymysql.err.IntegrityError as e:
        return {'code': 40041, 'msg': '用户名重复'}
    return {'code': 0, 'msg': '新增成功'}


@app.route("/api/users/<id>", methods=['get'])
def get_user(id):
    return User(*get(f'select * from user where id = {id}', 1)).to_dict()


@app.route("/api/users/<id>", methods=['put'])
def update_user(id):
    username = request.json.get('username')
    email = request.json.get('email')
    update(
        f"update user set username = '{username}',email = '{email}' where id = {id}")
    return {'code': 0, 'msg': '修改成功'}


@app.route("/api/users/<id>", methods=['delete'])
def remove_user(id):
    update(f'update user set status = 0 where id = {id}')
    return {'code': 0, 'msg': '删除成功'}


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')
